<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="说明" prop="description">
        <el-input v-model="formItem.description" type="textarea" :row="5" />
      </el-form-item>
      <el-form-item label="附件">
        <el-upload
          class="upload-demo"
          :headers="headers"
          :action="importUrl"
          :file-list="formItem.attachment"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-remove="handleRemove"
          :show-file-list="true"
        >
          <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getAttachment,
  attach,
  uploadFileUrl
} from '@neu/dcam-ui/api/fixedAsset'
import { getToken } from '@neu/biz-core/utils/auth'
import { deepClone } from '@neu/biz-core/utils'

// 定义一个表单原始项
const formItem = {
  id: '',
  description: '',
  attachment: [],
  assetId: ''
}
export default {
  name: 'AssetLifeCycleEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem,
        assetId: this.id
      },
      // 表单验证规则
      rules: {
        description: [{
          required: true,
          message: '分类名称不能为空',
          trigger: 'blur'
        }]
      },
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        getAttachment(this.id).then(response => {
          if (response.data) {
            const data = response.data
            if (data.attachment) {
              const fileJoins = data.attachment.split('||')
              data.attachment = fileJoins.map(it => {
                const fsInfo = it.split('@@')
                return {
                  fsId: fsInfo[0],
                  name: fsInfo[1]
                }
              })
            } else {
              data.attachment = []
            }
            this.formItem = {
              ...data
            }
          }
        })
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      // const updated = this.parentId !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          const deepCloneForm = deepClone(this.formItem)
          // 将附件转为字符串存储
          if (deepCloneForm.attachment.length > 0) {
            deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
          } else {
            deepCloneForm.attachment = ''
          }
          if (valid) {
            resolve(attach(deepCloneForm))
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    }
  }
}
</script>
